package sve.generator;

import java.util.ArrayList;

import sve.Utils;

import xadd.XADD;
import cmdp.HierarchicalParser;
import cmdp.TokenStream;

public class VOIGen {

	public static void generate(String filePath, int count) {
		String str = "";
		XADD x = new XADD();
		TokenStream t = new TokenStream();
		ArrayList<Integer> ids = new ArrayList<Integer>();
		ArrayList a;
		int id;

		t.read(getBlock("d > -10", getBlock("d < 10", "-0.01 * d * d + 0.001 * d + 1", "0"), "0"));
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		str = str + "d " + x.getString(id, false) + "\n";
		ids.add(id);

		t.read(getBlock("d > -10", getBlock("d < 10", "d", "0"), "0")); // getBlock("d > 0", , "0"))
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		str = str + "r1 delta " + x.getString(id, false) + "\n";
		ids.add(id);

		t.read(getBlock(
				"d > -10",
				getBlock(
						"d < 10",
						getBlock("d > 0",
								getBlock("d < 10", getBlock("d > 2.0", getBlock("d < 6.0", "d", "0.5"), "0.2"), "0"),
								"0"), "0"), "0"));
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		str = str + "r2 delta " + x.getString(id, false) + "\n";
		ids.add(id);

		t.read(getBlock("r1 > r2", "r1", "r2")); // getBlock("d < 3.0", "d", "0.5")
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		str = str + "o delta " + x.getString(id, false) + "\n";
		ids.add(id);

		t.read("([(-0.1 * o * o) + (5 * o) + 0.0])");
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		str = str + "u delta " + x.getString(id, false) + "\n";
		ids.add(id);

		Utils.print(filePath + ".sve", "bvariables ( ) \n case test\n " + str + "\nendcase");
	}

	protected static void write(XADD x, ArrayList<Integer> ids) {
		StringBuilder s = new StringBuilder("bvariables ( ) \n	case test\n	 ");

		for (int id : ids) {
			s.append(x.getString(id) + "\n");
		}

		Utils.print("./src/sve/VOI.sve", s.append("\nendcase").toString());
	}

	public static String getBlock(String cond, String tVal, String fVal) {
		return "( " + getElement(cond, true) + " " + getElement(tVal, false) + " " + getElement(fVal, false) + " )";
	}

	private static String getElement(String s, boolean cond) {
		if (s.contains("(")) {
			return s;
		} else if (s.contains("[")) {
			return "( " + s + " )";
		} else if (cond)
			return "[ " + s + " ]";

		return "( [ " + s + " ] )";
	}
}
